package com.caigou.modules.famous.ui.publish

import android.os.Bundle
import android.text.TextUtils
import androidx.activity.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseActivity
import com.caigou.comm.base.ext.*
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.famous.adpter.PublishBallItemAdapter
import com.caigou.modules.famous.bean.PublishItemBean
import com.caigou.modules.famous.databinding.ActivityPublishDetailBinding
import com.caigou.modules.famous.viewmodel.PublishViewModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/12/13
 */
@Route(path = RouterPath.Famous.PAGE_PUBLISH_DETAIL)
@AndroidEntryPoint
class PublishDetailActivity : BaseActivity() {

    private lateinit var binding: ActivityPublishDetailBinding

    private val publishViewModel: PublishViewModel by viewModels()

    @JvmField
    @Autowired(name = AppConstants.FAMOUS_TYPE)
    var famousType: Int = 1

    @JvmField
    @Autowired(name = AppConstants.FAMOUS_POST_TYPE)
    var famousPostType: Int = 0

    @Autowired(name = AppConstants.FAMOUS_PUBLISH_ITEM_BEAN)
    lateinit var publishItemBean: PublishItemBean

    private var limit = 0
    private var spanCount = 0
    private var items = mutableListOf<String>()
    private var balls = mutableListOf<String>()
    private var currentCheckNum = 0

    private lateinit var mAdapter: PublishBallItemAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPublishDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)
        containerId = binding.publishDetailLlContainer.id
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)
        limit = when (publishItemBean.dareTypeId) {
            18, 19, 25, 26, 27, 29, 34, 36, 37, 38, 39, 42 -> 1
            23, 24, 28, 40, 41 -> 2
            11, 30, 32 -> 3
            12, 31 -> 6
            33 -> 7
            13 -> 9
            else -> 0
        }

        items = when (publishItemBean.dareTypeId) {
            11, 12, 13, 18, 23, 34, 41 -> animals
            19, 24, 31, 33, 40 -> tails
            25 -> danShuang
            26 -> daXiao
            27 -> jiaYe
            28 -> shuangBo
            29 -> heDanShuang
            30, 36 -> heads
            32, 39 -> fiveElements
            38 -> parts
            42 -> banBo
            else -> mutableListOf()
        }

        spanCount = when (publishItemBean.dareTypeId) {
            11, 12, 13, 18, 23, 34, 41 -> 6
            19, 24, 30, 31, 32, 33, 36, 39, 40 -> 5
            25, 26, 27, 29 -> 2
            28, 42 -> 3
            38 -> 4
            else -> 0
        }

        mAdapter = PublishBallItemAdapter(items) { buttonView, isChecked ->
            if (isChecked) {
                if (currentCheckNum < limit) {
                    currentCheckNum++
                    balls.add(buttonView.text.toString())
                    changeContentTxt()
                } else {
                    showToast("最多选择${limit}个")
                    buttonView.isChecked = false
                }
            } else {
                currentCheckNum--
                balls.remove(buttonView.text.toString())
                changeContentTxt()
            }
        }
        binding.publishDetailRecyclerView.run {
            layoutManager = GridLayoutManager(this@PublishDetailActivity, spanCount)
            adapter = mAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(this@PublishDetailActivity))
        }

        binding.publishDetailTvTitle.text = "${publishItemBean.period}期"
        binding.publishDetailTvType.text = publishItemBean.dareTypeName
        binding.publishDetailTvContent.text = "${publishItemBean.dareTypeName}："

        binding.publishDetailTvRecord.setOnClickListener {
            ARouter.getInstance().build(RouterPath.Famous.PAGE_MY_RECORD).navigation()
        }

        binding.publishDetailBtnPublish.setOnClickListener {
            publishChallenge()
        }

        binding.publishDetailTvBack.setOnClickListener {
            finish()
        }
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(publishViewModel.publishChallengeLiveData, ::handlePublishChallenge)
    }

    private fun handlePublishChallenge(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("发布挑战异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data == null) {
                    return
                }
                showToast(result.data!!)
                LiveDataBus.get().with(BusKey.CHALLENGE_PUBLISH_FINISH, Any::class.java).value = Any()
                finish()
            }
        }
    }

    private fun publishChallenge() {
        val content = binding.publishDetailTvContent.text.toString().substringAfter("：")
        val remark = binding.publishDetailTvRemark.text.toString()
        publishViewModel.publishChallenge(
            content,
            content,
            publishItemBean.dareTypeId,
            famousType,
            famousPostType,
            publishItemBean.challengeRecordId,
            remark,
            AppBackgroundInfo.instance.userBean!!.userId
        )
    }

    private fun changeContentTxt() {
        if (balls.isNullOrEmpty()) {
            return
        } else {
            val content: StringBuilder = StringBuilder("${publishItemBean.dareTypeName}：")
            for (index in 0 until balls.size) {
                if (index == 0) {
                    content.append("-")
                }
                content.append(balls[index]).append("-")
            }
            binding.publishDetailTvContent.text = content
        }
    }
}